package com.enjoyor.soa.traffic.frame.configure;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import com.enjoyor.soa.traffic.frame.resolver.ResultErrorResoler;
import com.enjoyor.soa.traffic.frame.resolver.impl.DefaultResultErrorResolver;
import com.enjoyor.soa.traffic.util.exception.ManagerException;
import com.enjoyor.soa.traffic.util.exception.RestException;
import com.enjoyor.soa.traffic.util.exception.SignificantRestException;

@Configuration
@ComponentScan(basePackages = { "com.enjoyor.soa.traffic.frame.handler.exception" })
public class ExceptionConfig {

    @Bean
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public ResultErrorResoler defaultResultErrorResolver() {
        DefaultResultErrorResolver defaultResultErrorResolver = new DefaultResultErrorResolver();
        defaultResultErrorResolver.setDefaultExCode(500);
        defaultResultErrorResolver.setDefaultExMsg("未知原因，访问服务器错误！");
        defaultResultErrorResolver.setLocaleResolver(new AcceptHeaderLocaleResolver());

        ReloadableResourceBundleMessageSource defaultMessageSource = new ReloadableResourceBundleMessageSource();
        defaultMessageSource.setBasename("classpath:exception/messages");
        defaultResultErrorResolver.setMessageSource(defaultMessageSource);

        Map<String, String> exceptionMappingDefinitions = new HashMap();
        exceptionMappingDefinitions.put(SignificantRestException.class.getName(), "_exmsg");
        exceptionMappingDefinitions.put(RestException.class.getName(), "_exmsg");
        exceptionMappingDefinitions.put(ManagerException.class.getName(), "_exmsg");
        exceptionMappingDefinitions.put("Throwable", "500, server.error");

        defaultResultErrorResolver.setExceptionMappingDefinitions(exceptionMappingDefinitions);

        return defaultResultErrorResolver;
    }

}
